var url = document.location.toString();
var arrUrl = url.split("//");
var start = arrUrl[1].indexOf("/");
var relUrl = arrUrl[1].substring(0,start);
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
var Request = new Object();
Request = GetRequest();
window.onload=function(){
    //定义一个set保存取得的值
    postJson = new Map();
    //点击选择图片 设置id
    $("#InvoiceType a").bind("click",function(){
        if($(this).find("img").attr("src")=="../../img/Checkbox_on.png"){
            $(this).find("img").attr("id","false");
            $(this).siblings().find("img").attr("id","false");
            $(this).find("img").attr("src","../../img/Checkbox_off_light.png");
        }else{
            $(this).find("img").attr("id","true");
            $(this).siblings().find("img").attr("id","false");
            $(this).find("img").attr("src","../../img/Checkbox_on.png");
        }
        $(this).siblings().find("img").attr("src","../../img/Checkbox_off_light.png");
    });

   //判断是android还是IOS系统
    function checkOS() {
        var ua = navigator.userAgent.toLowerCase();
        if (/iphone|ipad|ipod/.test(ua)) {
            return "IOS";
        } else if (/android/.test(ua)) {
            return "Android";
        }
    }
//o家APP初始ios 注册
    function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    }
//ios调用
    setupWebViewJavascriptBridge(function(bridge) {
        bridge.registerHandler('testJSFunction', function(data, responseCallback) {
            responseCallback('js执行过了');
        })
    })
    //点击返回上一页
    $(".head-contain>a").click(function() {
        //调用原生的返回上一页方法
        if(checkOS()=="Android")
        {
            maojia.mjGoBack();
        } else{
            setupWebViewJavascriptBridge(function(bridge) {
                bridge.callHandler('mjGoBack', function(response) {
                })
            })
        }
    })
}
//点击提交校验  弹出确认框
$(".payment-button>button").click(function(){

    //判断发票类型  0是个人 1是企业
    if($("#InvoiceType #true").length>0){
        if(Trim($("#true").parent("a").text())=="个人/非企业"){
            postJson.set("InvoiceHead","0");
        }else{
            var flag = validateNull(".mustWrite");
            //检验必填项  填入非空标记 .mustWrite
            if(flag == "false"){
               // alert("必填项请输入");
                pageAlert("必填项请输入")
                return false;
            }
            postJson.set("InvoiceHead","1");
        }
    }else{
        alert('发票类型有误')
        pageAlert("发票类型有误")
    }

    //公司名称
    var InvoiceName = $("#InvoiceName").find("input").val();
    //税号
    var InvoiceTaxNo = $("#InvoiceTaxNo").find("input").val();
    //地址电话
    var InvoiceAddress = $("#InvoiceAddress").find("input").val();
    //开户银行
    var InvoiceBankName = $("#InvoiceBankName").find("input").val();
    //金额
    var InvoiceMoney = $("#InvoiceMoney").find("input").val();
    //邮箱
    var InvoiceEmail = $("#InvoiceEmail").find("input").val();
    //手机号
    var InvoicePhone = $("#InvoicePhone").find("input").val();

    postJson.set("InvoiceName",InvoiceName);
    postJson.set("InvoiceTaxNo",InvoiceTaxNo);
    postJson.set("InvoiceAddress",InvoiceAddress);
    postJson.set("InvoiceBankName",InvoiceBankName);
    postJson.set("InvoiceMoney",InvoiceMoney);
    postJson.set("InvoiceEmail",InvoiceEmail);
    postJson.set("InvoicePhone",InvoicePhone);

    var dialogHTML =`<div class="dialog-group-content">
        <div class="dialog-group">
            <label>名称:</label>
            <p>${InvoiceName}
               </p>
        </div>
        <div class="dialog-group">
            <label>税号:</label>
            <p>${InvoiceTaxNo}</p>
        </div>
        <div class="dialog-group">
            <label>地址电话:</label>
            <p>${InvoiceAddress}</p>
        </div>
        <div class="dialog-group">
            <label>开户账号:</label>
            <p>${InvoiceBankName}</p>
        </div>
        <div class="dialog-group">
            <label>金额:</label>
            <p><ins>${InvoiceMoney}</ins></p>
        </div>
        <div class="dialog-group">
            <label>电子邮箱:</label>
            <p>${InvoiceEmail}</p>
        </div>
        <div class="dialog-group">
            <label>手机号码:</label>
            <p>${InvoicePhone}</p>
        </div>
    </div>`;

    //弹出框
    $.dialog.confirm({
        width : 89.3,			//对话框宽度
        left : 5.3,             //距离左边  百分比
        top : 15,             //距离上边  百分比
        opentime : 280,			//对话框打开所用时间，单位为毫秒
        closetime : 280,		//对话框关闭所用时间，单位为毫秒
        mask : true,			//是否使用遮罩
        title : '确认提示',			//标题
        url : null,				//加载路径
        data : null,			//传送数据
        content:dialogHTML,         //内容
        callback:"ajaxPost();"
    });
});

//--------------------------------模糊搜索项目begin--------------------------------------
//实现搜索功能
$("#invoiceTitle-search").change(function () {
    inputChange();
})
//1：搜索数据
var inputChange = function () {
    var inputValue = $("#invoiceTitle-search").val();

    if (inputValue != "") {
        $.ajax({
            url: '/invoice/title',
            type: 'post',
            async: true,
            data: {
                "companyName": inputValue,
                "taxId": ""
            },
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (data) {
                console.log(data);
                if (data != "fail") {
                    _initItems(data);
                }
            },
            error: function () {
                // alert("操作失败");
            }
        })
    }
};
var maxFontNumber = 0;//最大字数
var suggestContainer = $('<div></div>'); //创建一个子<ul>
suggestContainer.attr('id', "testInput-suggest");
suggestContainer.attr('tabindex', '0');
suggestContainer.attr('css',$("html").css("font-size"))
suggestContainer.hide();
//2：初始化搜索到的数据进行显示
var _initItems = function (items) {
    suggestContainer.empty();
    for (var i = 0; i < items.length; i++) {
        if (items.length > maxFontNumber) {
            maxFontNumber = items.length;
        }
        var suggestItem = $('<div></div>'); //创建一个子<li>
        suggestItem.attr('id', items[i].taxId);
        id = items[i].taxId;
        suggestItem.append(items[i].name);
        suggestItem.css({
            'width': '100%',
            'padding': ' 0.44rem 0.5066666666666667rem  ',//item间距
            'word-wrap': 'break-word',
            'word-break': 'normal',
            'cursor': 'pointer',
            'background-color': '#ffffff',//默认背景颜色
            'color': 'rgba(21,21,21,0.87)',//默认字体颜色
            'text-align': 'left',
            'border-bottom': '1px solid rgb(204,204,204)',
            'font-size':'.4266666666666667rem',
            'font-family': 'PingFangSC-Regular'
    });
        suggestItem.bind("mouseover",
            function () {
                $(this).css({
                    'background-color': ' #F7F7F7',//选中背景颜色
                    'color': '#00001E;'//选中字体颜色
                });
            });
        suggestItem.bind("mouseout",
            function () {
                $(this).css({
                    'background-color': '#ffffff',//默认背景颜色
                    'color': '#00001E;'//默认字体颜色
                });
            });
        suggestItem.bind("click", showClickTextFunction);//选中后处理数据
        //suggestItem.bind("click", itemSelectFunction);
        suggestItem.appendTo(suggestContainer);
        suggestContainer.appendTo(document.body);
    }
    //添加图片
    var suggestImg = $('<img src="../img/bg_xialaocaidan(1).png"/>');
    suggestImg.attr("id","suggestImgId")
    suggestImg.appendTo(document.body)
    suggestContainer.removeAttr("style");
    suggestContainer.css({
        'border': '1px solid #ccc',
        'max-height': '2.6666666666666665rem ',
        'top': $('#invoiceTitle-search').offset().top+parseInt($(".panel-item-content").css('padding-top'))+parseInt($("#invoiceTitle-search").css("height")),
        'left': $('#invoiceTitle-search').offset().left - 37,
        'width': $('#invoiceTitle-search').width()+35+parseInt($("#invoiceTitle-search").css("margin-left")),//获取项目的宽度加上边框边距+左边偏移量+Input框的左边距
        'position': 'absolute',
        'font-size': '0.4266666666666667rem;',//默认字体大小
        'font-family': 'PingFangSC-Regular;',
        'z-index': 99999,
        'background-color': '#EEE',
        'overflow-y': 'auto',
        'overflow-x': 'hidden',
        'paddding-left': '0!important',
        'margin-left': '0!important',
        'color': '#00001E'

    });
    //图片定位
    suggestImg.css({
        'width': '0.8rem',
        'height': '0.26666666666666666rem',
        'z-index': 1000000,
        'position': 'absolute',
        'top': $('#invoiceTitle-search').offset().top+parseInt($("#suggestImgId").css("height")),
        'left':$('#invoiceTitle-search').offset().left+parseInt($("#suggestImgId").css("width"))-36
    })
    maxFontNumber = 0;
    suggestContainer.show();
};

//3.选中后处理数据
var showClickTextFunction = function () {
    $("#invoiceTitle-search").val($(this).text());
    suggestContainer.hide();
    $("#suggestImgId").remove();
};

//4.点击空白地方 隐藏
$(document).bind("click", function (e) {
    var target = $(e.target);
    if (target.closest(".pop").length == 0) {
        suggestContainer.hide();
    }
})

function pageAlert(txt,title){
    txt = txt ||'';
    title = title ||'提示';
    var $body =$('body');
    var $alert = $body.find('#alertPanel');
    if(!$alert.length){
        var html =  '<div class="page-alert-wrapper" id="alertPanel">'+
            '<span class="page-jumbotron" id="alertJumbotron"></span>'+
            '<div class="page-alert">'+
            '<header class="page-title" id="alertTitile">提示</header>'+
            '<div class="page-content" id="alertContent">'+
            '</div>'+
            '<footer class="page-footer"  id="alertBtn">确认</footer>'+
            '</div></div>';
        $body.append(html);
        $alert = $body.find('#alertPanel');
    }

    $('#alertTitile').text(title);   //设置标题
    $('#alertContent').text(txt);    //设置中间内容
    $('#alertPanel').show();    //弹框显示
    $('#alertPanel').off().on('click','#alertBtn,#alertJumbotron',function(){
        $('#alertPanel').hide();
    })
}
//-------------------------模糊搜索项目end------------------------------------------------

function ajaxPost(){
    $.ajax({
        url:'/invoice/openByApp',
        type:'POST', //GET
        async:true,    //或false,是否异步
        contentType: 'application/json;charset=UTF-8',
        data:JSON.stringify({
            guid:Request["invoiceId"],
            buyerName:postJson.get('InvoiceName'),
            buyerTaxNo:postJson.get('InvoiceTaxNo'),
            buyerAddressPhone:postJson.get('InvoiceAddress'),
            buyerBankAccount:postJson.get('InvoiceBankName'),
            buyerEmail:postJson.get('InvoiceEmail'),//邮箱
            buyerPhone:postJson.get('InvoicePhone'),//电话
            headType:postJson.get('InvoiceHead'),
            invoiceTypeCode:'026'//发票类型 手机端默认都为电子票026
        }),
        dataType:'text',
        success:function(data){
            window.open(arrUrl[0] + "//" + relUrl + "/invoice/appInvoiceSuccess","_self");
        },
        error:function(xhr,textStatus,errorThrown){
           // alert()
            pageAlert("开票失败")
        }
    })
}
function  validateNull(className) {
    var flag;
    $(className).each(function(){
        if($(this).find("input").length != 0){
            //检查 input有值
            if($(this).find("input").val() ==""){
                flag = "false";
                return false;
            }
            flag ="true";
        }else{
            //检查类选择
            if($(this).find("#true").length ==0){
                flag ="false";
                return false;
            }
            flag ="true";
        }
    });
    return flag;
}
//去掉字符串空格
function Trim(str)
{
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
